//
//  PageCollectionVC.swift
//  JTYP
//
//  Created by Groot on 2017/12/9.
//  Copyright © 2017年 inspur. All rights reserved.
//
import MJRefresh
import Alamofire

class FindCollectionVC: BaseCollectionVC {
    
    var kHeaderHeight: CGFloat = 0
    var dataSource = [CGSize]()
    let originalPageNumber = 1
    var notices = [Notice]()
    var headerNotices = [Notice]()
    // 通知类型
    var noticeType: NoticeType = NoticeType.nomal
    // 是否滚动
    var rollType: NoticeRollType = NoticeRollType.nomal
    
     init(collectionViewLayout layout: UICollectionViewLayout, type: NoticeType = NoticeType.nomal) {
        
        noticeType = type
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        creatDataSource()
        if isSmallIphone() {
            kHeaderHeight = 170
        }else {
            kHeaderHeight = 190
        }
        
        self.collectionView?.register(UINib.init(nibName: "FindNormalCell", bundle: nil), forCellWithReuseIdentifier: FindNormalCell.CellIdentifier)
        self.collectionView?.register(UINib.init(nibName: "FindHealthCell", bundle: nil), forCellWithReuseIdentifier: FindHealthCell.CellIdentifier)
        self.collectionView?.register(UINib.init(nibName: "FindFlexibleCell", bundle: nil), forCellWithReuseIdentifier: FindFlexibleCell.CellIdentifier)
        self.collectionView?.register(ScrollImageHeader.self, forCellWithReuseIdentifier: ScrollImageHeader.CellIdentifier)
        self.collectionView?.mj_header.beginRefreshing()
        
        request(start: originalPageNumber, forHeaderImg: true)
    }
    
    func creatDataSource(){
        for _ in 0..<5{
            let width = CGFloat(arc4random_uniform(100) + 50)
            let height = CGFloat(arc4random_uniform(100) + 50)
            dataSource.append(CGSize(width: width, height: height))
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func request(start: Int, forHeaderImg: Bool = false) {
        
        var params = Parameters()
        params["type"] = noticeType.rawValue
        params["roll"] = forHeaderImg ?
            NoticeRollType.roll.rawValue : NoticeRollType.nomal.rawValue
        params["start"] = start
        params["size"] = forHeaderImg ? 5 : 10
        params["orderBy"] = "createtime desc"
        
        NetWorkUtil.shareInstance.postForObject(objectType: ListResponse<Notice>.self, urlString: Server.noticeList, parameters: params, finishCallBack: ({ [unowned self](obj, error) in
            
            guard !forHeaderImg else {
                guard let result = obj?.data, result.count > 0 else {
                    return
                }
                self.headerNotices.removeAll()
                self.headerNotices += result
                self.collectionView?.reloadSections(IndexSet.init(integer: IndexSet.Element.init(bitPattern: 0)))
                return
            }
            
            self.bgPlaceholderView.removeFromSuperview()
            self.collectionView?.mj_header.endRefreshing( )
            self.collectionView?.mj_footer.endRefreshing()
            
            guard error == nil else{
                if start == self.originalPageNumber {
                    self.view.addSubview(self.errorPageView)
                    // 加载出错提示
                    self.errorPageView.error(handler: {
                        self.collectionView?.mj_header.beginRefreshing()
                    })
                }else {
                    self.view.makeToast("加载出错")
                }
                return
            }
            
            guard let result = obj?.data, result.count > 0 else{
                self.collectionView?.mj_footer.endRefreshingWithNoMoreData()
                if start == self.originalPageNumber {
                    self.view.addSubview(self.errorPageView)
                    // 无数据提示
                    self.errorPageView.empty("暂无相关内容", handler: {
                        self.collectionView?.mj_header.beginRefreshing()
                    })
                }
                return
            }
            if start == 1 {
                self.notices.removeAll()
            }
            self.notices += result
            self.collectionView?.reloadData()
        }))
    }
    @objc override func reload() {
        self.collectionView?.mj_footer.resetNoMoreData()
        request(start: originalPageNumber)
    }
    
    @objc override func loadMore() {
        if notices.count > 0 {
            request(start: notices.count + 1)
        }
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return notices.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ScrollImageHeader.CellIdentifier, for: indexPath) as! ScrollImageHeader
            cell.backgroundColor = .clear
            cell.setDatas(notices: headerNotices)
            return cell
        }
        if noticeType == NoticeType.health {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FindHealthCell.CellIdentifier, for: indexPath) as! FindHealthCell
            cell.backgroundColor = .clear
            cell.setData(obj: notices[indexPath.row])
            return cell
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FindNormalCell.CellIdentifier, for: indexPath) as! FindNormalCell
        cell.backgroundColor = .clear
        cell.setData(obj: notices[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize.init(width: self.view.bounds.size.width, height: kHeaderHeight)
        }
        if noticeType == NoticeType.health {
            return CGSize.init(width: self.view.bounds.size.width, height: 90)

        }
        return CGSize.init(width: self.view.bounds.size.width, height: 80)
    }
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
}



